<template>
<div>
  <!-- Main content -->
    <section class="content clearfix">
    <!--数据展示-->
     <div class="table clearfix">
       <div class="addBrandDiv">
        <el-button type="primary" class="addBrand"  data-toggle="modal"
                    data-target="#modal-default" @click="addRole" v-if="$_has('sys:role:add')">新增角色</el-button>
       </div>
        <el-table
          ref="roleList"
          :data="roleList"
          tooltip-effect="dark"
          style="width: 100%;font-size:14px;"
          :header-cell-style="{background:'#F5F7FA',height:'60px','line-height':'60px',color:'#606266','font-size':'14px'}"
          @selection-change="handleSelectionChange">
          <el-table-column
          label="序号" min-width="8%"  align="center"  >
          <template slot-scope="scope">
              {{scope.$index+1}}
            </template>
          </el-table-column>
          <el-table-column
         prop="role_name"
            label="角色名称"
          min-width="10%"  align="center" >
          </el-table-column>
          <el-table-column
            prop="remark"
            label="角色描述"
            min-width="20%"  align="center" >
          </el-table-column>
          <el-table-column
            prop="count"
            label="成员数量"
            min-width="10%"
            show-overflow-tooltip  align="center" >
          </el-table-column>
          <el-table-column
          fixed="right"
          label="操作"
          min-width="10%"  align="center" >
          <template slot-scope="scope">
            <div class="myicon-option">
              <i class="el-icon-myedit" title="编辑"  @click="editorRole(scope.row.role_id)" data-toggle="modal"
                          data-target="#modal-default" v-if="$_has('sys:role:edit')"></i>
              <i class="el-icon-mydelete"  title="删除"  @click="deleteRoleComfirm(scope.row.role_id)"
                         v-if="$_has('sys:role:del')"></i>
                        </div>
          </template>
        </el-table-column>
        </el-table>
        <el-pagination class="page" v-if="roleList.length != 0"
            background
            layout="total,prev, pager, next"
            :total="pages.total"
            :pager-count="6"
            :page-size="pages.display"
            @current-change ='pagechange'
            >
        </el-pagination>
      </div>
  </section>

  <section class="content">
    <div class="modal fade" id="modal-default">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">{{action=='add'?'新增':'编辑'}}角色</h4>
          </div>
          <div class="modal-body">
            <div class="form-horizontal">
              <div class="box-body">
                <div class="form-group">
                  <div class="col-sm-6 flex">
                    <label class="control-label min-width"><span class="sup">*</span>角色名称：</label>
                    <div class="inline-block">
                      <input type="text" class="form-control" placeholder="请输入角色名称" v-model="roleParams.roleName">
                    </div>
                  </div>
                  <div class="col-sm-6 flex">
                    <label class="control-label min-width">描述：</label>
                    <div class="inline-block">
                      <input type="text" class="form-control" placeholder="请输入描述" v-model="roleParams.remark">
                    </div>
                  </div>
                </div>
                <div class="box box-info">
                  <div class="box-header with-border bg-info">
                    <h3 class="box-title">权限分配</h3>
                  </div>
                  <div class="box-body">
                    <el-tree
                      :data="depositMenus"
                      show-checkbox
                      :default-checked-keys="menusId"
                      node-key="menuId"
                      ref="tree"
                      highlight-current
                      :props="defaultProps">
                      <!--:check-strictly="true"-->
                    </el-tree>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-primary"  @click="submitAuthority">保存</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
          </div>
        </div>
        <!-- /.modal-content -->
      </div>
      <!-- /.modal-dialog -->
    </div>
    <ul>
    </ul>
  </section>
  <!-- /.content -->
</div>
</template>

<script>
  import pagination from '@/components/common/pageComponent'
  import instance from '@/api/index.js'
  import {setCookie,getCookie} from "@/js/common/util";
  export default {
    name:"roleManagement",
    components: {
      pagination,
    },
    data(){
      return{
        show:false,//loading
        treeMenusData:[],//所有菜单数据
        topMenusData:[],//一级菜单数据
        sliderMenusData:[],//当前左侧菜单
        menusList:[],
        menuListCheck:[],
        depositMenus:[],
        menusIndex:0,
        roleList:[],//获取角色列表
        roleListParam:{},//获取角色列表传参
        pages:{
          total:0,//总页数
          current:1,//当前页
          display: 10,//显示条数
        },
        pageNum:1,//序号
        parentLevel:[],//菜单权限
        parentId:[],
        childrenId:[],
        chChildren:[],
        lastChildren:[],
        roleParams:{
          roleName:'',
          remark:''
        },
        menusId:[],
        defaultCheck:[],
        dataObj : [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        action: ""
      }
    },

    methods: {
       //获得当前选中数据
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      getCheckedNodes() {
        console.log(this.$refs.tree.getCheckedNodes());
      },
      getCheckedKeys() {
        console.log(this.$refs.tree.getCheckedKeys());
      },
      getHalfCheckedNodes:function(){
        console.log(this.$refs.tree.getHalfCheckedNodes())
      },
      setCheckedKeys() {
        this.$refs.tree.setCheckedKeys([3]);
      },
      // 获取分页
      pagechange: function (currentPage) {
        this.roleListParam.page = currentPage;
        this.pages.current = currentPage;
         this.roleListParam.rows = this.pages.display;
        this.getRoleList();
      },

      //获取角色列表
      getRoleList:function () {
        let vm = this;
        this.show = true;
        instance.post("/role/getUserRole",vm.roleListParam).then(function (data) {
          vm.show = false;
          vm.roleList = data.data.data.list;
          vm.pages.total = data.data.data.total;
        })
      },

      //获取角色详情
      editorRole:function (roleId) {
        let vm = this;
        this.roleParams.roleId = roleId;
        vm.menusId = [];
        this.action = "edit";
        instance.post("/role/getRoleDetail/" + roleId).then(function (data) {
          vm.roleParams.roleName = data.data.data.roleName;
          vm.roleParams.remark = data.data.data.remark;
          for (let j = 0; j < data.data.data.menus.length; j++){
            vm.menusId.push(data.data.data.menus[j].menuId)
          }
          console.log(vm.menusId)
          window.tree = vm.$refs.tree;
          // vm.$refs.tree.setCheckedKeys(vm.menusId, true);
          vm.$refs.tree.setCheckedKeys(vm.menusId);
        })
      },

      //获取用户菜单列表
      getMenusList:function (id) {
        let vm = this;
        instance.post('/menu/menuList',{userId:id}).then(function (data) {
          if(data.data.success){
            let menus = data.data.data;
            vm.treeMenusData = vm.toTreeData(menus);
            console.log(vm.treeMenusData)
          }
        })
      },

      //新增角色
      addRole:function(){
        this.roleParams.roleId = "";
        this.roleParams.roleName = "";
        this.roleParams.remark = "";
        this.action = "add";
        this.$refs.tree.setCheckedKeys([]);
      },

      //删除角色
      deleteRoleComfirm:function(_id){
        let vm = this;
        vm.$confirm('此操作将删除此角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: ''
        }).then(() => {
          // instance.post('/v1/warehouse/updateWareHouse',{roleId: _id}).then(function (data) {
            vm.deleteRole(_id)
            // vm.getRoleList();
          // })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        })
      },
      //删除角色
      deleteRole:function(id){
        let vm = this;
        instance.post('/role/deleteUserRole',{"roleId":id}).then(function (data) {
          if(data.data.success){
            vm.getRoleList();
          }
          vm.alertMessage(data.data);
        })
      },

      //提交角色表单
      submitAuthority:function(){
        let vm = this;
        if(!vm.roleParams.roleName){
          vm.$alert('请选择角色名', '提示', {
            confirmButtonText: '确定',
          });
          return;
        }
        this.menusId = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys());
        // this.menusId = this.$refs.tree.getCheckedKeys();
        let roleSubmit = {
          role:{},
        };
        roleSubmit.role.roleName = vm.roleParams.roleName;
        roleSubmit.role.remark = vm.roleParams.remark;
        roleSubmit.menuIds = vm.menusId;
        let postURL = "";
        if(this.roleParams.roleId){
          roleSubmit.role.roleId = vm.roleParams.roleId;
          postURL = "/role/editUserRole"
        }else {
          postURL = "/role/addUserRole"
        }
        instance({
          method:'post',
          url:postURL,
          data:roleSubmit
        }).then(function (data) {
          console.log(data)
          if(data.data.success){
            $("#modal-default").modal('hide');
          }
          vm.alertMessage(data.data);
          vm.getRoleList();
        })
      },
      alertMessage: function (value) {
        let type = 'success'
        if (!value.success) {
          type = 'error'
        }
        this.$message({
          showClose: false,
          message: value.msg,
          type: type
        });
      },
      getSetting: function () {
        let vm = this;
        let userInfo =getCookie("userId") ;
        if(userInfo){
          instance.post('/menu/menuList').then(function (data) {
            if(data.data.success){
              let menus = data.data.data;
              vm.getData(0,menus);
              vm.depositMenus = [];
              for (let i = 0; i < vm.menuListCheck.length; i++){
                if(vm.menuListCheck[i].parentId == 0){
                  vm.depositMenus.push(vm.menuListCheck[i])
                }
              }
              console.log(vm.depositMenus)
            }
          })
        }
      },

      getData: function (id, arry) {
        let vm = this;
        var childArry = this.familyTree(id, arry);
        if (childArry.length > 0) {
          for (var i = 0; i < childArry.length; i++) {
            let obj = {};
            obj = childArry[i];
            childArry[i].children = this.familyTree(childArry[i].menuId, arry);
            childArry[i].show = false;
            vm.menuListCheck.push(obj);
            vm.getData(childArry[i].menuId, arry);
          }
        }
      },
      //
      familyTree: function (id, arry) {
        var newArry = new Array();
        for (var i in arry) {
          if (arry[i].parentId == id)
            newArry.push(arry[i]);
        }
        return newArry;
      },

      toTreeData : function(data) {
        let resData = data;
        let tree = [];

        //组装一级菜单
        for (let i = 0; i < resData.length; i++) {
          if (resData[i].parentId === 0) {
            let obj = {
              id: resData[i].menuId,
              code: resData[i].menuId + resData[i].name,
              name: resData[i].name,
              parentId: resData[i].parentId,
              type:resData[i].type,
              children: []
            };
            tree.push(obj);
            resData.splice(i, 1);
            i--;
          }
        }
        run(tree);
        //递归组装所有下级菜单
        function run(chiArr) {
          if (resData.length !== 0) {
            for (let i = 0; i < chiArr.length; i++) {
              for (let j = 0; j < resData.length; j++) {
                if (chiArr[i].id === resData[j].parentId) {
                  let obj = {
                    id: resData[j].menuId,
                    code: resData[j].menuId + resData[j].name,
                    name: resData[j].name,
                    status: '启用',
                    remark: '测试数据测试数据',
                    parentId: resData[j].parentId,
                    type:resData[j].type,
                    children: []
                  };
                  chiArr[i].children.push(obj);
                  resData.splice(j, 1);
                  j--;
                }
              }
              run(chiArr[i].children);
            }
          }
        }
        return tree;
      }
    },
    created() {
      //获取角色列表数据
      this.getRoleList();

      //获取用户菜单列表
      this.getMenusList(1);

      this.getSetting();
    }
  }
</script>

<style lang="less" scoped type='text/css'>
  .role-table {
    border: 1px solid #e0e0e0;
    border-bottom: none;
    padding: 0;
    position: relative;
  }

  .header {
    height: 40px;
    line-height: 40px;
    border-bottom: 1px solid #e7e7e7;
    background: #F8F8F9;
    text-align: center;
  }

  .vertical-line {
    width: 1px;
    height: 100%;
    background: #ddd;
    position: absolute;
    left: 30%;
    top: 0
  }

  .left {
    width: 30%;
    float: left;
    padding-left: 10px;
    user-select: none;
    cursor: pointer;
  }

  .one {
    padding-left: 20px;
  }

  .right {
    width: 70%;
    float: left;
    padding-left: 10px;
  }

  .item-icon {
    margin-left: -5px;
    padding: 5px;
  }

  .line {
    clear: both;
    width: 100%;
    height: 1px;
    background: #e0e0e0;
  }
  .h40{
    height: 39px;
    line-height: 39px;
  }
  [v-cloak] {
    display: none;
  }

  //v2
  .content{
    .el-button {
        padding: 12px 20px;
    }
    .table{
      font-size: 14px;
      background: #fff;
      padding:20px;
      clear: both;
      overflow: hidden;
      .page{
        margin: 20px 0 5px;
        float: right;
      }
    .addBrandDiv{
      margin-bottom: 20px
    }

    .cell{
        display: flex;
        justify-content: center;
        align-items: center;
        .myicon-option{
          font-size: 18px;
          color: #409EFF;
          margin: 6px;
          cursor:pointer;

          i{
            display: inline-block;
            width: 18px;
            height: 18px;
            margin:  0 12px;
            &.el-icon-myedit{
              background:url('../../../assets/img/myEdit.png') no-repeat;
              background-size: 100%;
            }
            &.el-icon-mydelete{
                background:url('../../../assets/img/myDelete.png') no-repeat;
                background-size: 100%;
              }
          }
        }
    }
  }
}
//弹框
#modal-default{
  .modal-dialog{
    border-radius: 4px;
    background: #fff;
    .modal-header{
        border-radius: 4px 4px 0 0;
        background: #fff;
    }
    .control-label {
      color: #606266;
      font-weight: normal;
      font-size: 14px;
    }
    .form-control{
        line-height: 40px;
        height: 40px;
        border-radius: 4px;
    }
    .box-header.with-border{
      border-radius: 4px 4px 0 0;
      border-bottom: 1px solid #E4E7ED;
    }
    .box-header{
      padding: 10px 10px 10px 0;
          margin: 0 20px;
       &::before{
            content: "";
            display: inline;
            height: 30px;
            width: 2px;
            background-color: #409EFF;
            position: absolute;
            left: -20px;
            top: 10px;
        }
        }
      .bg-info{
        background: none;
      }

    .box{
      border-top: none;
      box-shadow:none;
      border-radius: 4px;
      border: 1px solid #E4E7ED;
    }
        border-radius: 4px;

    .btn-primary:hover, .btn-primary:active, .btn-primary.hover{
      background: #409EFF;
    }
    .btn-primary{
       background: #409EFF;
       border-color: #409EFF;
       width: 68px;
       height: 40px;
       border-radius: 4px;
    }
    .modal-footer .btn + .btn{
       width: 68px;
       height: 40px;
    }
    .box-body{
      padding-bottom: 0;
    }
    .modal-footer{
      border: none;
      text-align: center;
      padding-bottom: 40px;
    }
  }
  .sup{
      margin-right: 3px;
      color: #FF5655;
}
}


</style>
